<?php
namespace app\api\util;

class OSSHelper
{
    /**
     * 获取回调参数
     * @param  string $pid 广告牌id
     * @param  string $tab tab名称
     * @return [type]      [description]
     */
    public function postPolicy($pid = '', $order_type = '', $tab = 'constructors')
    {
        $bucket = config('ali_oss_bucket');
        $access_id = config('ali_oss_accessKeyId');
        $access_key = config('ali_oss_accessKeySecret');
        $url = config('ali_oss_url');//更改成你自己的地址
        
        $options['expiration'] = '2030-01-01T12:00:00.000Z'; /// 授权过期时间

        $conditions = array();
        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition; 

        array_push($conditions, array('bucket'=>$bucket));
        $dir = ''; // 文件名
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start; 
        $options['conditions'] = $conditions;
        $policy = base64_encode(stripslashes(json_encode($options)));
        $signature = base64_encode(hash_hmac('sha1', $policy, $access_key, true));//生成认证签名
        // 回调参数
        $callbackUrl = "http://workertest.bomeiyi.net/api/Aliyun/post_callback";
        $callback_param = array('callbackUrl'=>$callbackUrl, 
                     'callbackBody'=>'bucket=${bucket}&filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}&type=${imageInfo.format}&etag=${etag}&pid='.$pid.'&order_type='.$order_type.'&tab='.$tab, 
                     'callbackBodyType'=>"application/json");
        $callback_string = json_encode($callback_param);
        $base64_callback_body = base64_encode($callback_string);


        $return = [
            'bucket'    =>  $bucket,
            'access_id' =>  $access_id,
            // 'access_key'    =>  $access_key,
            'url'       =>  $url,
            'policy'    =>  $policy,
            'callback'  =>  $base64_callback_body,
            'signature' =>  $signature,
        ];
        return $return;
    }

    /**
     * 获取回调
     * @return [type] [description]
     */
    public function postCallback()
    {
        // 1.获取OSS的签名header和公钥url header
        $authorizationBase64 = "";
        $pubKeyUrlBase64 = "";
        
        if (isset($_SERVER['HTTP_AUTHORIZATION']))
        {
            $authorizationBase64 = $_SERVER['HTTP_AUTHORIZATION'];
        }
        if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL']))
        {
            $pubKeyUrlBase64 = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
        }

        if ($authorizationBase64 == '' || $pubKeyUrlBase64 == '')
        {
            header("http/1.1 403 Forbidden");
            exit();
        }

        // 2.获取OSS的签名
        $authorization = base64_decode($authorizationBase64);

        // 3.获取公钥
        $pubKeyUrl = base64_decode($pubKeyUrlBase64);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pubKeyUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $pubKey = curl_exec($ch);
        if ($pubKey == "")
        {
            //header("http/1.1 403 Forbidden");
            exit();
        }

        // 4.获取回调body
        $body = file_get_contents('php://input');

        // 5.拼接待签名字符串
        $authStr = '';
        $path = $_SERVER['REQUEST_URI'];
        $pos = strpos($path, '?');
        if ($pos === false)
        {
            $authStr = urldecode($path)."\n".$body;
        }
        else
        {
            $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
        }

        // 6.验证签名
        $ok = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
        if ($ok == 1)
        {
            header("Content-Type: application/json");
            $data = array("Status"=>"Ok", "body"=>$body);
            // return json($data);
            return $data;
        }
        else
        {
            //header("http/1.1 403 Forbidden");
            exit();
        }
    }
}